package com.example.sprintboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.sprintboot.entity.Role;
import com.example.sprintboot.entity.User;
import com.example.sprintboot.exception.DuplicateUsernameException;
import com.example.sprintboot.exception.InvalidCredentialsException;
import com.example.sprintboot.mapper.UserMapper;
import com.example.sprintboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public List<User> selectAllUsers() {
        return userMapper.selectList(null);
    }

    @Override
    public boolean saveUser(User user) {
        return userMapper.insert(user) > 0;
    }

    @Override
    public boolean updateUser(User user) {
        return userMapper.updateById(user) > 0;
    }

    @Override
    public boolean deleteUserById(Integer userId) {
        return userMapper.deleteById(userId) > 0;
    }

    @Override
    public User selectUserById(Integer userId) {
        return userMapper.selectById(userId);
    }

    @Override
    @Transactional
    public User register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (existingUser != null) {
            throw new DuplicateUsernameException("用户名已存在");
        }

        // 设置默认角色
        if (user.getRole() == null) {
            user.setRole(Role.BUYER); // 默认设置为买家
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置时间戳
        LocalDateTime now = LocalDateTime.now();
        user.setCreateTime(now);
        user.setUpdateTime(now);

        // 保存用户
        userMapper.insert(user);
        return user;
    }

    @Override
    public User login(String username, String password) {
        // 根据用户名查找用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new InvalidCredentialsException("用户名或密码错误");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new InvalidCredentialsException("用户名或密码错误");
        }

        return user;
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    // 管理员端用户管理相关方法实现
    @Override
    public IPage<User> adminListUsers(int page, int pageSize, String role, Integer status, String keyword) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (role != null && !role.isEmpty()) wrapper.eq("role", role);
        if (status != null) wrapper.eq("status", status);
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.and(w -> w.like("username", keyword)
                              .or().like("phone", keyword)
                              .or().like("email", keyword));
        }
        Page<User> userPage = new Page<>(page, pageSize);
        return userMapper.selectPage(userPage, wrapper);
    }

    @Override
    public void toggleUserStatus(Integer id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            if (user.getStatus() != null && user.getStatus() == 1) {
                user.setStatus(0); // 禁用
            } else {
                user.setStatus(1); // 启用
            }
            userMapper.updateById(user);
        }
    }

    @Override
    public void resetUserPassword(Integer id) {
        User user = userMapper.selectById(id);
        if (user != null) {
            String encoded = passwordEncoder.encode("123456");
            user.setPassword(encoded);
            userMapper.updateById(user);
        }
    }

    @Override
    public void deleteUserByAdmin(Integer id) {
        userMapper.deleteById(id);
    }
}
